using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using AudioStudio.Components;
using Cinemachine;
using DG.Tweening;
using NpcFramework;
using NpcFramework.Traffic;
using OWL.Rendering.HRP;
using UnityEditor;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.SceneManagement;
using Object = UnityEngine.Object;

namespace Gameplay.PVE.Editor
{
    public class RpgSceneGenerator : EditorWindow
    {
        private bool isLightMap = false;
        private bool isReflectionProbe = false;
        private bool isCamera = false;
        private bool isUnits = false;
        private bool isObstacle = false;
        private bool isHidePoint = false;
        private bool isMainUnitRegion = false;
        private bool isFog = false;
        private bool isRenderScene = false;
        private static RpgBattleSceneData sceneData;
        void OnGUI()
        {
            float startX = 30;
            float startY = 20;
            isLightMap = GUI.Toggle(new Rect(startX, startY, 100, 30), isLightMap, "lightMap");
            startY += 40;
            isReflectionProbe = GUI.Toggle(new Rect(startX, startY, 100, 30), isReflectionProbe, "isReflectProbe");
            startY += 40;
            isCamera = GUI.Toggle(new Rect(startX, startY, 100, 30), isCamera, "isCamera");
           
            startY += 40;
            isUnits = GUI.Toggle(new Rect(startX, startY, 100, 30), isUnits, "isUnits");
            startY += 40;
            isFog = GUI.Toggle(new Rect(startX, startY, 100, 30), isFog, "isFog");
            startY += 40;
            isRenderScene = GUI.Toggle(new Rect(startX, startY, 100, 30), isRenderScene, "isRenderScene");
            startY += 40;
            isObstacle = GUI.Toggle(new Rect(startX, startY, 100, 30), isObstacle, "isObstacle");
            startY += 40;
            /*isHidePoint = GUI.Toggle(new Rect(startX, startY, 100, 30), isHidePoint, "isHidePoint");
            startY += 40;
            isMainUnitRegion = GUI.Toggle(new Rect(startX, startY, 100, 30), isMainUnitRegion, "isMainUnitRegion");
            startY += 40;*/
            if (GUI.Button(new Rect(startX, startY, 100, 30), "generate"))
            {
                GenerateAll();
            }
        }
        
        private void GenerateReflectionProbe(GameObject root)
        {
            var sceneName = SceneManager.GetActiveScene().name;
            var reflectionProbes = root.GetComponentsInChildren<ReflectionProbe>();
            sceneData.reflectionProbes.Clear();
            sceneData.reflectionProbesTextures.Clear();
            for (int i = 0; i < reflectionProbes.Length; i++)
            {
                string st = "Assets/ResourcesAssets/Pve/Textures" + string.Format("/{1}_reflectionProbe-{0}.exr",i,sceneName);
                if (reflectionProbes[i].mode == ReflectionProbeMode.Baked)
                {
                    var tp = AssetDatabase.GetAssetPath(reflectionProbes[i].bakedTexture);
                    AssetDatabase.CopyAsset(tp, st);
                }
                else if (reflectionProbes[i].mode == ReflectionProbeMode.Custom)
                {
                    var tp = AssetDatabase.GetAssetPath(reflectionProbes[i].customBakedTexture);
                    AssetDatabase.CopyAsset(tp, st);
                }
                var texture = AssetDatabase.LoadAssetAtPath<Cubemap>(st);
                sceneData.reflectionProbes.Add(reflectionProbes[i]);
                sceneData.reflectionProbesTextures.Add(texture);
            }
        }
        
        private void GenerateLightMap(GameObject root)
        {
            var sceneName = SceneManager.GetActiveScene().name;
            sceneData.meshList.Clear();
            sceneData.lightMapIndexList.Clear();
            sceneData.lightMapOffsetList.Clear();
            sceneData.lightMapPath.Clear();
            sceneData.lightMapDirPath.Clear();
            sceneData.lightMapTextures.Clear();
            sceneData.lightMapDirTextures.Clear();
            var meshRenderers = root.GetComponentsInChildren<MeshRenderer>();
            for (int i = 0; i < meshRenderers.Length; i++)
            {
                var meshRenderer = meshRenderers[i];
                if (meshRenderer.lightmapIndex >= 0)
                {
                    sceneData.meshList.Add(meshRenderer);
                    sceneData.lightMapIndexList.Add(meshRenderer.lightmapIndex);
                    sceneData.lightMapOffsetList.Add(meshRenderer.lightmapScaleOffset);
                }
            }

            for (int i = 0; i < LightmapSettings.lightmaps.Length; i++)
            {
                string st = "Assets/ResourcesAssets/Pve/Textures" + string.Format("/{1}_Lightmap-{0}_comp_light.tga",i,sceneName);
                var tp = AssetDatabase.GetAssetPath(LightmapSettings.lightmaps[i].lightmapColor);
                AssetDatabase.CopyAsset(tp, st);
                var texture = AssetDatabase.LoadAssetAtPath<Texture2D>(st);
                sceneData.lightMapTextures.Add(texture);
                sceneData.lightMapPath.Add(st);
                st = "Assets/ResourcesAssets/Pve/Textures" + string.Format("/{1}_Lightmap-{0}_comp_dir.png",i,sceneName);
                tp = AssetDatabase.GetAssetPath(LightmapSettings.lightmaps[i].lightmapDir);
                AssetDatabase.CopyAsset(tp, st);
                texture = AssetDatabase.LoadAssetAtPath<Texture2D>(st);
                sceneData.lightMapDirTextures.Add(texture);
                sceneData.lightMapDirPath.Add(st);
            }

            if (sceneData.lightingSetting == null)
            {
                var volumn = root.GetComponentInChildren<Volume>();
                if (volumn != null && volumn.transform.parent != null)
                {
                    sceneData.lightingSetting = volumn.transform.parent.gameObject;
                    volumn.transform.parent.SetParent(root.transform);
                    sceneData.lightingSetting.SetActive(false);
                }
            }
           
            if (sceneData.lightingSetting != null)
            {
                sceneData.lightingSetting.SetActive(false);
            }
        }

        private static void GenerateCamera(GameObject root)
        {
            var cameraObj = sceneData.gameObject.transform.Find("Camera");
            if (cameraObj)
            {
                var camera = cameraObj.GetComponent<Camera>();
                sceneData.overrideCamera = true;
                sceneData.sideCamera = camera;
                //cameraObj.SetActive(false);
            }

            cameraObj = root.transform.Find("Camera");
            if (cameraObj)
            {
                var camera = cameraObj.GetComponent<Camera>();
                /*
                var screenPoint = new Vector3(0, size.y / 2f);
                var ray = camera.ScreenPointToRay(screenPoint);
                var groundPoint = ray.origin - ray.direction * (ray.origin.y / ray.direction.y);*/
                var leftPoint = root.transform.Find("leftPoint");
                if (leftPoint)
                {
                    sceneData.leftCameraPoint = leftPoint.transform.position;
                    System.Type type = System.Type.GetType("UnityEditor.GameView,UnityEditor");
                    var s_GetSizeOfMainGameView = type.GetMethod("GetSizeOfMainGameView", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
                    var size = (Vector2)s_GetSizeOfMainGameView.Invoke(null, null);
                    sceneData.leftCameraPointScreenXRatio =
                        camera.WorldToScreenPoint(sceneData.leftCameraPoint).x / size.x;
                    leftPoint.gameObject.SetActive(false);
                }
                
                //cameraObj.SetActive(false);
            }

            sceneData.hasBackCamera = false;
            cameraObj = root.transform.Find("CameraBack");
            if (cameraObj)
            {
                sceneData.hasBackCamera = true;
                var camera = cameraObj.GetComponent<Camera>();
                sceneData.backCamera = camera;
            }
            
            var deckCameraObj = sceneData.gameObject.transform.Find("DeckCamera");
            if (deckCameraObj)
            {
                sceneData.overrideDeckCamera = true;
                var camera = deckCameraObj.GetComponent<Camera>();
                sceneData.deckCamera = camera;
                var leftPoint = root.transform.Find("leftPoint");
                if (leftPoint)
                {
                    System.Type type = System.Type.GetType("UnityEditor.GameView,UnityEditor");
                    var s_GetSizeOfMainGameView = type.GetMethod("GetSizeOfMainGameView", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
                    var size = (Vector2)s_GetSizeOfMainGameView.Invoke(null, null);
                    sceneData.deckLeftCameraPointScreenXRatio =
                        camera.WorldToScreenPoint(sceneData.leftCameraPoint).x / size.x;
                    //leftPoint.gameObject.SetActive(false);
                }
                //deckCameraObj.SetActive(false);
            }

            deckCameraObj = root.transform.Find("DeckCamera");
            if (deckCameraObj)
            {
                //deckCameraObj.SetActive(false);
            }
            
            var battleEndCamera = sceneData.gameObject.transform.Find("CameraBattleEnd");
            if (battleEndCamera)
            {
                sceneData.battleEndCamera = battleEndCamera.GetComponent<Camera>();
            }
        }

        private static void GenerateUnits(GameObject root)
        {
            var unitRoot =  root.transform.Find("[Units]");
            if (unitRoot)
            {
                var self = unitRoot.transform.Find("0");
                if (self)
                {
                    sceneData.selfPositions.Clear();
                    sceneData.selfForwards.Clear();
                    for (int i = 0; i < self.childCount; i++)
                    {
                        var child = self.GetChild(i);
                        if (child.name.Contains("Assist"))
                        {
                            sceneData.selfAssistPosition = child.position;
                        }
                        else
                        {
                            sceneData.selfPositions.Add(child.position);
                            sceneData.selfForwards.Add(child.forward);
                            if (i == 0)
                            {
                                sceneData.position = sceneData.gameObject.transform.position;
                            }
                        }
                    }
                }
                var enemy = unitRoot.transform.Find("2");
                if (enemy)
                {
                    sceneData.enemyPositions.Clear();
                    sceneData.enemyForwards.Clear();
                    for (int i = 0; i < enemy.childCount; i++)
                    {
                        var child = enemy.GetChild(i);
                        if (child.name.Contains("Assist"))
                        {
                            sceneData.enemyAssistPosition = child.position;
                        }
                        else
                        {
                            sceneData.enemyPositions.Add(child.position);
                            sceneData.enemyForwards.Add(child.forward);
                        }
                    }
                }
                //unitRoot.SetActive(false);
                sceneData.overrideUnits = true;
            }
        }
        
        private static void GenerateSound(GameObject root)
        {
            sceneData.effectSounds.Clear();
            var effectSound = root.GetComponentsInChildren<EffectSound>();
            for (int i = 0; i < effectSound.Length; i++)
            {
                effectSound[i].gameObject.SetActive(false);
                sceneData.effectSounds.Add(effectSound[i].gameObject);
            }
        }

        private void GenerateObstacleBlocks(GameObject root)
        {
            sceneData.blocks = new List<Vector3>();
            var obstacles = root.GetComponentsInChildren<RpgBattleSceneObstacle>();
            for (int i = 0; i < obstacles.Length; i++)
            {
                var blocks = obstacles[i].GetObstacleBlocks(sceneData.aStarCenter);
                sceneData.blocks.AddRange(blocks);
            }
        }

        private void GenerateHidePoint(GameObject root)
        {
            sceneData.hidePoints = new List<Vector3>();
            sceneData.attackPoints = new List<Vector3>();
            var hidePoint = root.GetComponentInChildren<BattleSceneHidePoint>();
            if (hidePoint)
            {
                var hidePointRoot = hidePoint.transform;
                for (int i = 0; i < hidePointRoot.childCount; i++)
                {
                    var child = hidePointRoot.GetChild(i);
                    if (child.name.Contains("hide"))
                    {
                        sceneData.hidePoints.Add(child.position);
                    }
                    else
                    {
                        sceneData.attackPoints.Add(child.position);
                    }
                }
            }
        }

        private void GenerateMainUnitRegion(GameObject root)
        {
            var mainUnitRegion = root.GetComponentInChildren<BattleSceneMainUnitRegion>();
            if (mainUnitRegion)
            {
                sceneData.mainUnitRegionAngle = mainUnitRegion.angle;
                sceneData.mainUnitRegionBottom = mainUnitRegion.bottom;
                sceneData.mainUnitRegionTop = mainUnitRegion.top;
                sceneData.mainUnitRegionLeft = mainUnitRegion.left;
                sceneData.mainUnitRegionRight = mainUnitRegion.right;
                sceneData.mainUnitRegionCenter = mainUnitRegion.transform.position;
            }
        }

        private void GenerateMeleeLine(GameObject root)
        {
            var meleeLine = root.GetComponentInChildren<BattleSceneMeleeLine>();
            if (meleeLine)
            {
                sceneData.meleeLineAngle = meleeLine.angle;
                sceneData.meleeLineCenter = meleeLine.transform.position;
                sceneData.meleeLineDistance = meleeLine.distance;
            }
        }

        private static void GenerateAStarRegion(GameObject root)
        {
            var region = root.GetComponentInChildren<BattleSceneAStarRegion>();
            if (region)
            {
                var center = Quaternion.FromToRotation(Vector3.forward,region.transform.forward) * new Vector3((region.left + region.right) / 2, 0, (region.top + region.bottom) / 2);
                var width = Mathf.Abs(region.left - region.right);
                var height = Mathf.Abs(region.top - region.bottom);
                sceneData.aStarCenter = center + region.transform.position;
                sceneData.aStarHeight = Mathf.CeilToInt(height / AStarMgr.gridSize.y);
                sceneData.aStarWidth = Mathf.CeilToInt(width / AStarMgr.gridSize.x);
                sceneData.battleRegionHeight = height;
                sceneData.battleRegionWidth = width;
                sceneData.propRegionSize = region.propCellSize;
                sceneData.propRegionHeight = region.propHeight;
                sceneData.propRegionWidth = region.propWidth;
            }
        }

        private static void GenerateEnemyPath(GameObject root)
        {
            sceneData.enemyPaths = new List<RpgBattleSceneEnemyPath>();
            sceneData.enemyPathId = new List<int>();
            var path = root.GetComponentsInChildren<RpgBattleSceneEnemyPath>();
            for (int i = 0; i < path.Length; i++)
            {
                path[i].GeneratePath();
                sceneData.enemyPaths.Add(path[i]);
                sceneData.enemyPathId.Add(i+100);
            }
        }
        
        private void GenerateAll()
        {
            var sceneName = SceneManager.GetActiveScene().name;
            var path = string.Format("Assets/ResourcesAssets/Pve/Prefabs/Others/{0}_scenePrefab.prefab",sceneName);
            var prefab = AssetDatabase.LoadAssetAtPath<GameObject>(path);
            var root = GameObject.Find("[Root]");
            var battleRoot = root.transform.Find("battle");
            if (battleRoot != null)
            {
                root = battleRoot.gameObject;
            }
            GameObject ppp = null;
            if (prefab)
            {
                ppp = GameObject.Instantiate(prefab);
                var bunkerHitPoint = ppp.GetComponent<BunkerHitPoint>();
                if (bunkerHitPoint)
                {
                    var newBunkerHitPoint = root.GetComponent<BunkerHitPoint>();
                    if (newBunkerHitPoint)
                    {
                        
                    }
                    else
                    {
                        newBunkerHitPoint = root.AddComponent<BunkerHitPoint>();
                        for (int i = 0; i < bunkerHitPoint.singlePoints.Count; i++)
                        {
                            //先保证路径是一样的
                            //获取路径
                            var oldObject = bunkerHitPoint.singlePoints[i].gameObject;
                            string p = string.Empty;
                            var newObject = GameObject.Instantiate(oldObject);
                            var parent = oldObject.transform;
                            while (true)
                            {
                                parent = parent.parent;
                                if (parent == ppp.transform || parent == null)
                                {
                                    break;
                                }

                                if (string.IsNullOrEmpty(p))
                                {
                                    p = parent.name + p;
                                }
                                else
                                {
                                    p = parent.name + "/" + p;
                                }
                               
                            }
                            var newParent = root.transform.Find(p);
                            if (newParent)
                            {
                                newObject.transform.SetParent(newParent);
                                newObject.transform.localPosition = oldObject.transform.localPosition;
                                newObject.transform.localEulerAngles = oldObject.transform.localEulerAngles;
                                newBunkerHitPoint.singlePoints.Add(newObject.GetComponent<BunkerSingleHitPoint>());
                            }
                            else
                            {
                                newObject.transform.position = oldObject.transform.position;
                                newObject.transform.forward = oldObject.transform.forward;
                                var hitPoint = newObject.AddComponent<BunkerSingleHitPoint>();
                                hitPoint.type = bunkerHitPoint.singlePoints[i].type;
                                hitPoint.luaType = bunkerHitPoint.singlePoints[i].luaType;
                                newBunkerHitPoint.singlePoints.Add(hitPoint);
                                Debug.LogError("[BunkerSingleHitPoint] 没有找到 "+p);
                            }
                        }

                        for (int i = 0; i < bunkerHitPoint.colliders.Count; i++)
                        {
                            var gameObject = bunkerHitPoint.colliders[i].gameObject;
                            string p = gameObject.name;
                            var parent = gameObject.transform;
                            while (true)
                            {
                                parent = parent.parent;
                                if (parent == ppp.transform || parent == null)
                                {
                                    break;
                                }
                                p = parent.name + "/" + p;
                            }

                            var newObject = root.transform.Find(p);
                            if (newObject)
                            {
                                var collider = newObject.gameObject.AddComponent<BunkerHitPointCollider>();
                                collider.type = bunkerHitPoint.colliders[i].type;
                                collider.luaType = bunkerHitPoint.colliders[i].luaType;
                                collider.gameObject.GetOrAddComponent<BoxCollider>();
                                newBunkerHitPoint.colliders.Add(collider);
                            }
                            else
                            {
                                Debug.LogError("[BunkerHitCollider] 没有找到 "+p);
                            }
                        }
                    }
                }
                
                var sceneData = root.GetComponent<RpgBattleSceneData>();
                var oldSceneData = ppp.GetComponent<RpgBattleSceneData>();
                if (sceneData && oldSceneData)
                {
                    sceneData.overrideCamera = oldSceneData.overrideCamera;
                    sceneData.sideCamera = oldSceneData.sideCamera;
                    sceneData.deckCamera = oldSceneData.deckCamera;
                    sceneData.backCamera = oldSceneData.backCamera;
                    sceneData.overrideDeckCamera = oldSceneData.overrideDeckCamera;
                    sceneData.overrideUnits = oldSceneData.overrideUnits;
                    sceneData.selfPositions = oldSceneData.selfPositions;
                    sceneData.enemyPositions = oldSceneData.enemyPositions;
                    sceneData.selfAssistPosition = oldSceneData.selfAssistPosition;
                    sceneData.enemyAssistPosition = oldSceneData.enemyAssistPosition;
                }
            }
            
            if (root != null)
            {
                sceneData = root.GetOrAddComponent<RpgBattleSceneData>();
                
                sceneData.position = root.transform.position;
                sceneData.rotation = root.transform.eulerAngles;
                sceneData.overridePosition = true;
                var battleForward = root.transform.Find("BattleForward");
                if (battleForward)
                {
                    sceneData.battleForward = battleForward.forward;
                }
                if (isRenderScene)
                {
                    sceneData.renderScene = root.GetComponentInChildren<HBaseRenderScene>();
                    if (sceneData.renderScene == null)
                    {
                        //从场景里找
                        var renderScene = GameObject.FindObjectOfType<HBaseRenderScene>();
                        if (renderScene != null)
                        {
                            var newRenderScene = GameObject.Instantiate(renderScene,root.transform);
                            sceneData.renderScene = newRenderScene.GetComponent<HBaseRenderScene>();
                        }
                    
                    }
                }
               
                if (isLightMap)
                {
                    GenerateLightMap(root);
                }

                if (isReflectionProbe)
                {
                    GenerateReflectionProbe(root);
                }

                if (isCamera)
                {
                    GenerateCamera(root);
                }

                if (isUnits)
                {
                    GenerateUnits(root);
                }

                if (isObstacle)
                {
                    GenerateObstacleBlocks(root);
                }

                //if (isHidePoint)
                {
                    GenerateHidePoint(root);
                }
                
                //if (isMainUnitRegion)
                {
                    GenerateMainUnitRegion(root);
                }
                
                GenerateMeleeLine(root);

                GenerateAStarRegion(root);

                if (isFog)
                {
                    GenerateFog();
                }

                SaveLandscape();

                //车子相关
                var trafficCars = root.GetComponentsInChildren<TrafficCar>();
                for (int i = 0; i < trafficCars.Length; i++)
                {
                    trafficCars[i].enabled = false;
                }

                var trafficLights = root.GetComponentsInChildren<TrafficLight>();
                for (int i = 0; i < trafficLights.Length; i++)
                {
                    trafficLights[i].enabled = false;
                }

                var rigidBody = root.GetComponentsInChildren<Rigidbody>();
                for (int i = 0; i < rigidBody.Length; i++)
                {
                    Object.DestroyImmediate(rigidBody[i]);
                }

                var seeker = root.GetComponentsInChildren<TrafficCarSeeker>();
                for (int i = 0; i < seeker.Length; i++)
                {
                    seeker[i].enabled = false;
                }

                var collider = root.GetComponentsInChildren<Collider>();
                for (int i = 0; i < collider.Length; i++)
                {
                    collider[i].enabled = false;
                }

                AssetDatabase.SaveAssets();
                AssetDatabase.Refresh();
                var newObject = GameObject.Instantiate(root);
                var units = newObject.transform.Find("[Units]");
                if (units != null)
                {
                    /*var team0 = units.Find("0");
                    if (team0 != null)
                    {
                        var positions = new List<Vector3>();
                        for (int i = 0; i < team0.childCount; i++)
                        {
                            positions.Add(team0.GetChild(i).position);
                        }
                        while(positions[i])
                    }*/
                    GameObject.DestroyImmediate(units.gameObject);
                }

                var cameras = newObject.GetComponentsInChildren<Camera>();
                for (int i = 0; i < cameras.Length; i++)
                {
                    cameras[i].gameObject.SetActive(false);
                }
                PrefabUtility.SaveAsPrefabAsset(newObject, path);
                GameObject.DestroyImmediate(newObject);
                AssetDatabase.SaveAssets();
                AssetDatabase.Refresh();

                if (sceneData.lightingSetting)
                {
                    sceneData.lightingSetting.SetActive(true);
                }
            }

            if (ppp)
            {
                GameObject.DestroyImmediate(ppp);
            }
        }

        private void SaveLandscape()
        {
            var battleLandscape = FindObjectOfType<BattleSceneLandscapeRegion>();
            if (battleLandscape)
            {
                var path = string.Format("Assets/ResourcesAssets/Pve/Prefabs/Others/{0}_battleLandscape.prefab",SceneManager.GetActiveScene().name);
                var newObject = GameObject.Instantiate(battleLandscape.gameObject);
                var collider = newObject.GetComponent<Collider>();
                if (collider)
                {
                    Object.DestroyImmediate(collider);
                }
                PrefabUtility.SaveAsPrefabAsset(newObject.gameObject,path);
                AssetDatabase.SaveAssets();
                AssetDatabase.Refresh();
                sceneData.singleLandscapePath = path;
                GameObject.DestroyImmediate(newObject);
            }
        }

        private void GenerateFog()
        {
            sceneData.fog = true;//RenderSettings.fog;
            sceneData.fogColor = RenderSettings.fogColor;
            sceneData.fogDensity = RenderSettings.fogDensity;
            sceneData.fogMode = RenderSettings.fogMode;
            sceneData.fogStartDistance = RenderSettings.fogStartDistance;
            sceneData.fogEndDistance = RenderSettings.fogEndDistance;
        }

        public static void AutoAttachGround(RpgBattleSceneData data)
        {
            //出生点
            for (int i = 0; i < data.selfPositions.Count; i++)
            {
                var newPosition = PveScene.GetAttachGroundPoint(data.selfPositions[i]);
                data.selfPositions[i] = newPosition;
            }
            for (int i = 0; i < data.enemyPositions.Count; i++)
            {
                var newPosition = PveScene.GetAttachGroundPoint(data.enemyPositions[i]);
                data.enemyPositions[i] = newPosition;
            }
        }

        public static void SaveScene(RpgBattleSceneData data,string path)
        {
            var root = data.transform.gameObject;
            sceneData = data;
            sceneData.position = root.transform.position;
            sceneData.rotation = root.transform.eulerAngles;
            sceneData.overridePosition = true;
            var battleForward = root.transform.Find("BattleForward");
            if (battleForward)
            {
                sceneData.battleForward = battleForward.forward;
            }
        
            GenerateCamera(root);
            GenerateUnits(root);
            AutoAttachGround(sceneData);
            GenerateSound(root);
            /*GenerateObstacleBlocks(root);
            GenerateHidePoint(root);
            GenerateMainUnitRegion(root);
            GenerateMeleeLine(root);*/
            GenerateAStarRegion(root);
            GenerateEnemyPath(root);
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
            var newObject = GameObject.Instantiate(root);
            var units = newObject.transform.Find("[Units]");
            if (units != null)
            {
                /*var team0 = units.Find("0");
                if (team0 != null)
                {
                    var positions = new List<Vector3>();
                    for (int i = 0; i < team0.childCount; i++)
                    {
                        positions.Add(team0.GetChild(i).position);
                    }
                    while(positions[i])
                }*/
                /*var meshRenderers = units.GetComponentsInChildren<SkinnedMeshRenderer>();
                for (int i = 0; i < meshRenderers.Length; i++)
                {
                    if (meshRenderers[i].gameObject)
                    {
                        GameObject.DestroyImmediate(meshRenderers[i].gameObject);
                    }
                }*/
                GameObject.DestroyImmediate(units.gameObject);
            }

            var cameras = newObject.GetComponentsInChildren<Camera>();
            for (int i = 0; i < cameras.Length; i++)
            {
                cameras[i].gameObject.SetActive(false);
            }
            PrefabUtility.SaveAsPrefabAsset(newObject, path);
            GameObject.DestroyImmediate(newObject);
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();

        }
    }
}